package com.jiaming.employee.common.interceptor;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.jiaming.employee.common.exception.ApiException;
import com.jiaming.employee.common.utils.JwtInfo;
import com.jiaming.employee.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author dragon
 * @create 2020-10-24 20:43
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        log.info("SpringMVC Interceptor {}", "AuthInterceptor");

        String token = request.getHeader("access_token");
        if (StrUtil.isEmpty(token)) {
            token = request.getParameter("token");
        }
        if (StrUtil.isEmpty(token)) {
            throw new ApiException("无效token");
        }

        JwtInfo jwtInfo = JwtUtil.getSecretInfo(token);
        // 把账户信息自动添加到每次请求内容中。
        // 如果 controller 中有处理器使用账户信息，可以从 request 中获取
        request.setAttribute("accountId", jwtInfo.getId());
        request.setAttribute("loginName", jwtInfo.getLoginName());

        // 判断 token 中的内容是否过期
        if (JwtUtil.isExpired(jwtInfo.getExpiredDate())) {
            // 3天后过期
            jwtInfo.setExpiredDate(DateUtil.offsetDay(new Date(), 3));
            String newToken = JwtUtil.createSign(jwtInfo);
            response.setHeader("token", newToken);
        }

        return true;
    }
}
